package com.github.maojx0630.onebot.socket;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 毛家兴
 * @since 2024-04-02 09:22
 */
@Slf4j
@UtilityClass
public class OneBotUtil {
  private static final ConcurrentHashMap<String, WebSocketSession> CACHE = new ConcurrentHashMap<>();

  void put(String id, WebSocketSession session) {
    CACHE.put(id, session);
  }

  void remove(String id) {
    CACHE.remove(id);
  }

  @SneakyThrows
  public void send(String id, String message) {
    WebSocketSession session = CACHE.get(id);
    if (session != null && session.isOpen()) {
      session.sendMessage(new TextMessage(message));
    }
  }
}
